package cn.itcast.controller;


import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.PayLog;
import cn.itcast.service.OrderService;
import cn.itcast.service.PayLogService;
import cn.itcast.service.WebSocketServer;
import cn.itcast.service.WxPayService;
import cn.itcast.utils.ConvertUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/pay")
public class WxPayController {
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WebSocketServer webSocketServer;

    @Reference
    private OrderService orderService;

    @Reference
    private PayLogService payLogService;

    @RequestMapping("/wxPay")
    private Result wxPay(@RequestParam("orderId")String id) {
        String url = wxPayService.getUrl(id);
        if (url==null){
            return new Result(false,MessageConstant.QUERY_SETMEAL_FAIL,url);
        }
        return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, url);
    }

    //微信服务发送支付成功请求到传递路径地址
    @RequestMapping("/notify")
    private String wxPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取微信服务器字节流
        ServletInputStream is = request.getInputStream();
        //通过工具类转换微信服务器发送app用来校验的订单信息[xml格式]
        String strXML = ConvertUtils.convertToString(is);
        //转换为map[用于订单校验，默认成功]
        Map<String, String> map = WXPayUtil.xmlToMap(strXML);

        String orderId = map.get("out_trade_no");
        PayLog payLog = new PayLog();
        payLog.setOrderId(orderId); //订单id
        payLog.setTransactionId(map.get("transaction_id")); //交易id
        String total_fee = map.get("total_fee");
        double total = Double.parseDouble(total_fee);
        payLog.setMoney(total); //支付金额
        payLog.setPayStatus(1); //支付状态
        payLog.setPayTime(new Date());//支付时间

        //调用Api修改支付日志支付状态
        payLogService.updatePayStatus(payLog);



        //System.out.println("访问成功");

        //成功之后发送响应值给微信服务器，告诉接收完毕
        HashMap<String, String> resMap = new HashMap<>();
        //回复return_code
        resMap.put("return_code","SUCCESS");
        //转换为xml格式
        String sendXML = WXPayUtil.mapToXml(resMap);


        //修改数据库支付状态
        orderService.updatePayStatus(orderId);

        //发送给前端告诉支付成功，跳转页面
        webSocketServer.onMessage("SUCCESS");
        //@RestBody谁调用返回参数给调用者
        return sendXML;
    }
}